<?php
namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\AchievementVali;
use App\Http\Controllers\Validator\RoomInfoVail;
use App\Model\Account\SystemType;
use App\Model\Account\Type;
use App\Model\Backstage\Customers;
use App\Model\Backstage\RoomInfo;
use App\Model\Backstage\RoomWordbook;
use App\Model\Backstage\RoomWordbookInfo;
use App\Model\Backstage\User;
use App\Tool\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Support\Facades\Auth;

/**
 * Class RoomInfoController
 * @package App\Http\Controllers\Backstage
 * 房源信息控制器
 * date:2018-4-29
 */
class RoomInfoController extends Controller
{
    /**
     * 房源列表
     * Wu Ning
     */
    public function houseList (Request $request,RoomInfo $roomInfo, User $user, RoomWordbook $roomWordbook)
    {
//        $parameter = $request->all();
        //房源状态等于1 未删除房源
        $where[] = ['room_status',1];
        $param = $request->all();
        //房型   普通房  优质房
        if(isset($param['type_of_house_sale']) && $param['type_of_house_sale'] !=''){
            $where[] = ['type_of_house_sale' , $param['type_of_house_sale']];
        }
        //用途
        if(isset($param['use_type']) && $param['use_type'] != ''){
            $where[] = ['use_type' , $param['use_type']];
        }

        //面积
        if(isset($param['r_acreage_begin']) && $param['r_acreage_begin'] != ''){   //开始面积
            $where[] = ['r_acreage', '>=', $param['r_acreage_begin']];
        }
        if(isset($param['r_acreage_end']) && $param['r_acreage_end'] != ''){   //结束面积
            $where[] = ['r_acreage', '<=', $param['r_acreage_end']];
        }

        //状态
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status' , $param['status']];
        }
        //层高类型   高层  低层
        if(isset($param['housing_types']) && $param['housing_types'] != ''){
            $where[] = ['housing_types' , $param['housing_types']];
        }

//        //朝向
//        if(isset($param['r_orientation']) && $param['r_orientation'] != ''){
//            $where[] = ['r_orientation' => $param['r_orientation']];
//        }

        //楼层
        if(isset($param['floor_begin']) && $param['floor_begin'] != ''){  //开始楼层
            $where[] = ['floor', '>=', $param['floor_begin']];
        }
        if(isset($param['floor_end']) && $param['floor_end'] != ''){    //结束楼层
            $where[] = ['floor', '<=', $param['floor_end']];
        }
        //部门
        if(isset($param['r_d_id']) && $param['r_d_id'] !=''){
            $where[] = ['r_d_id',$param['r_d_id']];
        }
        //员工
        if(isset($param['source_uid']) && $param['source_uid'] != ''){
            $where[] = ['source_uid', $param['source_uid']];
        }

        //交易类型  仅租  仅售  租售
        if(isset($param['trading_type']) && $param['trading_type'] != ''){
            $where[] = ['trading_type', $param['trading_type']];
        }
//        //交易状态类型  有效  无效
        if(isset($param['trading_state_type']) && $param['trading_state_type'] != ''){
            $where[] = ['trading_state_type' ,$param['trading_state_type']];
        }

        //价格 给价格类型值 1按租价  2按售价
        $param['price_type'] = 1;  //对接数据时删除，现在做默认值测试
        if($param['price_type'] == 1){
            if(isset($param['begin_price']) && $param['begin_price'] != ''){
                $where[] = ['floor_price', '>=', $param['begin_price']];
            }
            if(isset($param['end_price']) && $param['end_price'] != ''){
                $where[] = ['floor_price', '<=', $param['end_price']];
            }
        }else{
            if(isset($param['begin_price']) && $param['begin_price'] != ''){
                $where[] = ['unit_price', '>=', $param['begin_price']];
            }
            if(isset($param['end_price']) && $param['end_price'] != ''){
                $where[] = ['unit_price', '<=', $param['end_price']];
            }
        }
        //录入时间
        if ($request->input('date_type') == 1){
            if ($param['start_time']) {
                $where[] = ['r_created_at', '>=', strtotime($param['start_time'])];
            }
            if ($param['end_time']) {
                $where[] = ['r_created_at', '<=', strtotime($param['end_time'])];
            }
        }
        //最后跟进时间
        if ($request->input('date_type') == 2){
            if ($param['start_time']) {
                $where[] = ['r_follow_time', '>=', strtotime($param['start_time'])];
            }
            if ($param['end_time']) {
                $where[] = ['r_follow_time', '<=', strtotime($param['end_time'])];
            }
        }
        //交房时间
        if ($request->input('date_type') == 3){
            if ($param['start_time']) {
                $where[] = ['making_room', '>=', strtotime($param['start_time'])];
            }
            if ($param['end_time']) {
                $where[] = ['making_room', '<=', strtotime($param['end_time'])];
            }
        }

        //建房年代
        if ($request->input('date_type') == 4){
            if ($param['start_time']) {
                $where[] = ['building_s', '>=', $param['start_time']];
            }
            if ($param['end_time']) {
                $where[] = ['building_s', '<=', $param['end_time']];
            }
        }
        //委托时间
        if($request->input('date_type') == 5){
            if($request->input('start_time')){
                $where[] = ['r_entrust_at', '>=', $param['start_time']];
            }
            if($request->input('end_time')){
                $where[] = ['r_entrust_at', '<=', $param['end_time']];
            }
        }
        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        $list = $roomInfo->listRoom(env('PAGE_LIMIT_ADMIN'), $where, $keywords);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        //  判断当前登陆员工的身份类型
        $data = $user->getUserType();
//        dd($data);
        $type = $data['type'];
        $uId = $data['uid'];
        foreach($list as $k=>$v){
            //盘类型(1 私盘  2 公盘 3 特盘 4封盘)
            //当房源类型等于 1、3时仅限个人看 房源重要信息隐藏（置空）
            // 2时大家都能看 此时信息不做处理
            //当房源类型等于4时需要特殊权限才能看，这个等人员权限加上时进行判断
            if ($v->source_uid != $uId && ($v->disc_type == 1 || $v->disc_type == 3) && $type == 1){
                $v->owner_name = '';
                $v->owner_phone='';
                $v->contact_name='';
                $v->contact_phone='';
            }
            $v->building_name = $roomWordbook->getWordbook($v->building_id); //楼盘字典
            $v->use_name    = Type::getTypeDetail($v->use_type);         //用途
            $v->housing_name = Type::getTypeDetail($v->housing_types);  //房屋类型
            $v->type_of_house_name = Type::getTypeDetail($v->type_of_house_sale);  //房屋出售类型
            $v->disc_name = Type::getTypeDetail($v->disc_type);    //盘类型  私盘  公盘
            $v->trading_name = Type::getTypeDetail($v->trading_type); //交易类型
            $v->trading_state_name = Type::getTypeDetail($v->trading_state_type); //交易状态类型
            $v->rents_name = Type::getTypeDetail($v->rents_type);            //租价类型
            $v->entrust_name = Type::getTypeDetail($v->entrust_way);    //委托方式
            $v->source_name = Type::getTypeDetail($v->source_type);    //来源id
            $v->status_quo_name = Type::getTypeDetail($v->status_quo);    //现状
            $v->decoration_name = Type::getTypeDetail($v->decoration);    //装修
            $v->furniture_name = Type::getTypeDetail($v->furniture);    //家具
            $v->appliance_name = Type::getTypeDetail($v->appliance);    //家电
            $v->rights_name = Type::getTypeDetail($v->rights_type);    //产权类型
            $v->certificate_name = Type::getTypeDetail($v->certificate_type);    //证件类型
            $v->payment_name = Type::getTypeDetail($v->payment_type);    //付款类型
            $v->pay_on_name = Type::getTypeDetail($v->pay_on_type);    //付拥类型
            $v->checking_way_name = Type::getTypeDetail($v->checking_way);    //看房方式
            //多选框数据循环查找
            $support_name = [];
            if($v->support){
                $support_arr = explode(',',$v->support);
                foreach($support_arr as $key => $val){
                    $support['id'] = $val;
                    $support['name'] = Type::getTypeDetail($val);    //'配套
                    array_push($support_name, $support);
                }
            }
            $v->support_name = $support_name;
            //根据用途变换的输入款  将数据库json字符串转换成数组
            $v->r_info = json_decode($v->r_info, true);
            //房源明细列表
            $v->r_detaile_list = json_decode($v->r_detaile_list, true);
        }
        return $this->success('ok', $list);
     }


    /**交易合同 诚意金  等简单查找房源列表接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function houseListFast(Request $request)
    {
        //房源状态等于1 未删除房源
        $where[] = ['room_status',1];
        $param = $request->all();
        //部门
        if ($request->input('r_d_id')){
            $where[] = ['r_d_id', $param['r_d_id']];
        }
        //录入人ID
        if ($request->input('source_uid')){
            $where[] = ['source_uid', $param['source_uid']];
        }
        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        //区县ID
        if ($request->input('a_id')){
            $where[] = ['a_id', $param['a_id']];
        }
        //交易
        if($request->input('trading_type')){
            $where[] = ['status' , $param['status']];
        }
        //状态
        if($request->input('status')){
            $where[] = ['status' , $param['status']];
        }
        $roomInfo = new RoomInfo();
        $list = $roomInfo->listRoomFast(env('PAGE_LIMIT_ADMIN'), $where, $keywords);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        $roomWordbook = new RoomWordbook();
        $roomwordbookinfo = new RoomWordbookInfo();
        foreach($list as $k=>$v){
            $v->trading_type = SystemType::getTypeDetail($v->trading_type);//交易类型
            $v->a_id = AreaController::getAreaName($v->a_id);//城区
            $v->building_id = $roomWordbook->getWordbook($v->building_id); //楼盘字典
            $v->few_building  = $roomwordbookinfo->getWordbookInfoName($v->few_building);//栋座
            $v->status = SystemType::getTypeDetail($v->status); //交易状态类型
        }
        return $this->success('ok', $list);

    }





    /**
     * 添加房源数据信息
     */
    public function insertHouse (Request $request,RoomInfo $RoomInfo, Customers $customers)
    {   //verificationRoomRepeat

        $params = $request->except('token');
        $validator =  RoomInfoVail::validate($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        //根据房源用途不同前台传的不同类型字段值,转换成json字符串，输出时直接转换成json数组前台取值
        $json_info = $request->input('r_info','{}');
        $params['r_info'] = json_encode($json_info);
        //房源明细列表 将前台提交的明细数组转换成json 以name值为键 对应输入框值
        $json_detaile = $request->input('r_detaile_list','{}');
        $params['r_detaile_list'] = json_encode($json_detaile);
        //写入房源之前验证房源是否重复
        $res = $RoomInfo->verificationRoomRepeat($params);
        if(!$res){
            return $this->error(Error::ADD_ERROR);
        }

        $res = $RoomInfo->addRoomInfo($params);
       // dd($res);
        if (!$res) {
            //添加失败
            return $this->error(Error::ADD_ERROR);
        }
        //按租售类型查找
        $map[] = ['c_trading_type',$params['trading_type']]; //此处要求 客源和房源交易类型ID必须保持一致
        //按价格查找
        if(intval($params['trading_type']) == 1){  //录入为售房 查询条件按租价查找客源
            $map[] = ['c_price_min', '<=', $params['price']];
            $map[] = ['c_price_max', '>=', $params['price']];
        }elseif(intval($params['trading_type']) == 2){   //录入房源为租时查找需要租的价格匹配客源
            $map[] = ['c_rent_price_min', '<=', $params['rents']];
            $map[] = ['c_rent_price_max', '>=', $params['rents']];
        }else{
            $map[] = ['c_price_min', '<=', $params['price']];
            $map[] = ['c_price_max', '>=', $params['price']];
            $map[] = ['c_rent_price_min', '<=', $params['rents']];
            $map[] = ['c_rent_price_max', '>=', $params['rents']];
        }
        //按面积查找
        if($request->has('r_acreage') && $params['r_acreage'] !=''){
            $map[] = ['c_acreage_min', '<=', $params['r_acreage']];
            $map[] = ['c_acreage_max', '>=', $params['r_acreage']];
        }
        //智能匹配返回相对应客源列表
        $customers_list = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
        return $this->success('ok', $customers_list);
    }

   /*
    * 修改房源
    * Wu Ning
    * 2018 05 27
    */
    public function updataHouse(Request $request,RoomInfo $RoomInfo, Customers $customers)
    {
        $params = $request->except('token');
        $validator =  RoomInfoVail::validate($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $RoomInfo->updataHouse($params);
        if (!$res) {
            //修改失败
            return $this->error(Error::ADD_ERROR);
        }
        //按租售类型查找
        $map[] = ['c_trading_type',$params['trading_type']]; //此处要求 客源和房源交易类型ID必须保持一致
        //按价格查找
        if(intval($params['trading_type']) == 1){  //录入为售房 查询条件按租价查找客源
            $map[] = ['c_price_min', '<=', $params['price']];
            $map[] = ['c_price_max', '>=', $params['price']];
        }elseif(intval($params['trading_type']) == 2){   //录入房源为租时查找需要租的价格匹配客源
            $map[] = ['c_rent_price_min', '<=', $params['rents']];
            $map[] = ['c_rent_price_max', '>=', $params['rents']];
        }else{
            $map[] = ['c_price_min', '<=', $params['price']];
            $map[] = ['c_price_max', '>=', $params['price']];
            $map[] = ['c_rent_price_min', '<=', $params['rents']];
            $map[] = ['c_rent_price_max', '>=', $params['rents']];
        }
        //按面积查找
        if($request->has('r_acreage') && $params['r_acreage'] !=''){
            $map[] = ['c_acreage_min', '<=', $params['r_acreage']];
            $map[] = ['c_acreage_max', '>=', $params['r_acreage']];
        }
        //智能匹配返回相对应客源列表
        $customers_list = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
        return $this->success('ok', $customers_list);
    }

    /**
     * @param Request $request
     * @param RoomInfo $roomInfo
     * @return \Illuminate\Http\JsonResponse
     * 获取房源详细信息 可用于编辑  查看详细信息
     */
    public function infoHouse(Request $request, RoomInfo $roomInfo){
        if(!$request->input('id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $info = $roomInfo->getRoomInfo($request->input('id'));
        return $this->success('ok', $info);
    }

    /*
     * 软删除
     */
    public function softDelHouse(Request $request,RoomInfo $RoomInfo)
    {
        $params = $request->all();
        if($params['id']){
            $res = $RoomInfo->softDelHouse($params['id']);
        }else{
            return $this->error(Error::ADD_ERROR);
        }
        if (!$res) {
            //修改失败
            return $this->error(Error::ADD_ERROR);
        }
        return $this->success('ok', '删除成功');

    }

    /*
     *  永久删除房源
     */
    public function DelHouse(Request $request,RoomInfo $RoomInfo)
    {
        $id = $request->input('id');
        if($id){
            $res = $RoomInfo->DelHouse($id);
        }else{
            return $this->error(Error::PARAM_MISSING);
        }
        if (!$res) {
            //修改失败
            return $this->error(Error::DEL_ERROR);
        }
        return $this->success('ok', '删除成功');
    }

    /**
     * 房源结算业绩分配
     */
    public function addAchievement(Request $request,RoomInfo $roomInfo){

        $param = $request->all();
        if(!AchievementVali::validate($param)){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $roomInfo->saveRoomStatus($param);
        if($res['code'] == 1){
            return $this->success('ok', $res['msg']);
        }else{
            return $this->error(Error::ADD_ERROR);
        }
    }

    //添加房源的时候获取当前省市区   以及 默认各种类型
    public function getDefaultType()
    {
        $area_list = DB::table('area')->where(['parentId' => $this->city_code])->get();
        $data = [
            'area_list'         => $area_list,
            'province_code'     => $this->province_code,
            'city_code'         => $this->city_code,
            'city_name'         => $this->city,
        ];
        //《住宅、商住、其他》  房型40、厅57、卫65、阳台73、用途1、优选度27、
        //盘类型34、类型204、朝向81、交易92、状态96、
//        $arr = [40,57,65,73,1,27,34,204,81,92,96,106,704,111,118,128,136,147,576,219,603,679,233];
        $data['roomtype'] =  SystemType::storageRedis(40);//房型
        $data['hall'] =  SystemType::storageRedis(57);//厅
        $data['guard'] =  SystemType::storageRedis(65);//卫
        $data['balcony'] =  SystemType::storageRedis(73);//阳台
        $data['use'] =  SystemType::storageRedis(1);//用途
        $data['optimal'] =  SystemType::storageRedis(27);//优选度
        $data['plate'] =  SystemType::storageRedis(34);//盘类型
        $data['zsq_type'] =  SystemType::storageRedis(204);//《住宅、商住、其他》--- 类型
        $data['oriented'] =  SystemType::storageRedis(81);//朝向
        $data['transaction'] =  SystemType::storageRedis(92);//交易
        $data['status'] =  SystemType::storageRedis(96);//状态
        //包税费106、租价单位704、委托方式111、来源118、
        //付款128、 付佣136、看房 147
        //《商铺  铺厂 网点》   位置 576  层数 219
        //《写字楼 写厂》  级别603
        //《车位》 位置679     排量 233
        $data['package'] =  SystemType::storageRedis(106);//包税费
        $data['rentunit'] =  SystemType::storageRedis(704);//租价单位
        $data['delegation '] =  SystemType::storageRedis(111);//委托方式
        $data['source'] =  SystemType::storageRedis(118);//来源
        $data['payment'] =  SystemType::storageRedis(128);//付款
        $data['commission'] =  SystemType::storageRedis(136);//付佣
        $data['lookhouse'] =  SystemType::storageRedis(147);//看房
        $data['spw_position'] =  SystemType::storageRedis(576);//《商铺  铺厂 网点》位置
        $data['numlayers'] =  SystemType::storageRedis(219);//层数
        $data['level'] =  SystemType::storageRedis(603);//级别
        $data['c_position'] =  SystemType::storageRedis(679);//车位--位置
        $data['displacement'] =  SystemType::storageRedis(233);//排量

        //《商铺  铺厂 网点》----类型 237
        $data['spw_type'] =  SystemType::storageRedis(237);

        //《写字楼  写厂》-----类型  277
        $data['xx_type'] =  SystemType::storageRedis(277);

        //厂房 仓库-----类型  362
        $data['cc_type'] =  SystemType::storageRedis(362);

        //地皮-----类型  369
        $data['dp_type'] =  SystemType::storageRedis(369);

        //车位---------类型  394
        $data['c_type'] =  SystemType::storageRedis(394);



        //住宅、商住、其他 -----现状  152
        $data['zsq_statusquo'] =  SystemType::storageRedis(152);

        //商铺、 铺厂、 网点 -----现状  243
        $data['spw_statusquo'] =  SystemType::storageRedis(243);

        //写厂  写字楼  -----现状  284
        $data['xx_statusquo'] =  SystemType::storageRedis(284);

        //厂房、仓库、地皮 --现状  314
        $data['ccd_statusquo'] =  SystemType::storageRedis(314);

        //车位------现状
        $data['c_statusquo'] =  SystemType::storageRedis(375);


        //产权  156

        //装修  162

        //证件  172

        //配套  182

        //家具  188

        //家电  196

        //类型  204

        return $this->success('ok', $data);
    }







}